#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>

int missing_int(int *a, int n)
{
    int i, *b;
    int iSize;

    iSize = sizeof(int) * (n+1);
    b = (int *)malloc(iSize);
    if (b == NULL) {
	printf("malloc %d bytes failed.\n", iSize);
	return -1;
    }
    memset(b, 0, iSize); 

    for (i=0; i<n; i++) {
	b[a[i]] = 1;
    }
    for (i=0; i <=n; i++)
	if(b[i] == 0) {
	    free(b);
	    return i;
	}

    free(b);
    return -1;
}

int gen_array(int *a, int n, int iMiss)
{
    int i, iPos;

    if (iMiss < 0 || iMiss > n)
	return -1;
    printf("to miss %d\n", iMiss);

    for ( i=0; i < n; i++)
	a[i] = -1;

    srand(time(NULL));
    for ( i=0; i <= n; i++) {
	if (i == iMiss)
	    continue;
	while (1) {
	    iPos = rand() % n;
	    if (a[iPos] != -1)
	       continue;	
	    a[iPos] = i;
	    break;
	}
    }
    return 0;
}

int print_a(int *a, int n)
{
    int i;
    if (n <= 0)
	return -1;	

    printf("a[%d]:\t", n);
    for (i = 0; i < n; i++) {
	printf("%d\t", a[i]);
	if ((i+1) % 8 == 0)
	    printf("\n\t");
    }
    return 0;
}

int main(int argc, char *argv[])
{
    int a[8];
    int iLen;
    
    iLen = sizeof(a) / sizeof(a[0]);
    srand(time(NULL));
    gen_array(a, iLen, rand() % (iLen+1));
    print_a(a, iLen); 
    printf("found miss:%d\n", missing_int(a, iLen));

    return 0;
}
